package scatter.wxminiapp.rest.basic.service.impl.handler;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scatter.wxminiapp.pojo.po.WxMaMsgReply;
import scatter.wxminiapp.rest.basic.service.handler.IMaDefaultEnhanceHandler;
import scatter.wxminiapp.rest.basic.service.handler.IMaDefaultHandler;
import scatter.wxminiapp.rest.componentext.IMaMsgReplyParser;
import scatter.wxminiapp.rest.service.IWxMaMsgReplyService;

import java.util.List;
import java.util.Map;

/**
 * Created by yangwei
 * Created at 2021/11/22 18:57
 */
@Slf4j
@Service
public class IMaDefaultHandlerImpl implements IMaDefaultHandler {

    @Autowired(required = false)
    private List<IMaDefaultEnhanceHandler> iMaDefaultEnhanceHanderList;
    @Autowired
    private IWxMaMsgReplyService iMaMsgReplyService;


    @Autowired(required = false)
    private List<IMaMsgReplyParser> iMaMsgReplyParsers;

    @Override
    public WxMaXmlOutMessage handle(WxMaMessage wxMessage, Map<String, Object> context, WxMaService wxMaService, WxSessionManager sessionManager) throws WxErrorException {

        // 优先执行增强处理器
        if (iMaDefaultEnhanceHanderList != null) {
            for (IMaDefaultEnhanceHandler iMaDefaultEnhanceHander : iMaDefaultEnhanceHanderList) {
                if (iMaDefaultEnhanceHander.support(wxMessage,context,wxMaService,sessionManager)) {
                    return iMaDefaultEnhanceHander.handle(wxMessage,context,wxMaService,sessionManager);
                }
            }
        }
        // 自定义规则处理
        if (iMaMsgReplyParsers != null) {
            WxMaMsgReply matched = iMaMsgReplyService.getMatched(wxMessage, context, wxMaService, sessionManager);
            if (matched != null) {
                for (IMaMsgReplyParser iMaMsgReplyParser : iMaMsgReplyParsers) {
                    if (iMaMsgReplyParser.support(matched)) {
                        return iMaMsgReplyParser.parse(matched, wxMessage, context, wxMaService, sessionManager);
                    }
                }
            }
        }


        return null;
    }
}
